<?php
namespace Admin\Controller;
use Think\Controller;

class OrdersController extends HomeController {
	/*
	* Function:		ordersList
	* Description:	订单列表
	*/
    public function ordersList(){
		$filter = I('param.');
		$page =  I('get.p',1);
		$pageSize = 10;
		$filter = returnFilter($filter);
		$ordersList = D('Orders')->getOrdersList($page,$filter,$pageSize);
		if(is_array($ordersList)&&count($ordersList)>0){
			foreach($ordersList as $key=>$val){
				if(!empty($val['user_id'])){
					$userInfo = D('User')->getUserInfo($val['user_id']);
					$ordersList[$key]['username'] = emojiDecode($userInfo['username']);
					$ordersList[$key]['avatarurl'] = $userInfo['avatarurl'];
				}
			}
		}
		$count =  D('Orders')->getOrdersCount($filter);
		$pages = getpage($count,$pageSize,$filter);
		$show = $pages->show();
		$this->assign('ordersList',$ordersList);
		$orderStatusList = D('Orders')->getOrderStatusList();
		$syncStatusList = [['value'=>'0','name'=>'未同步'],['value'=>'1','name'=>'已同步']];
		$this->assign('orderStatusList',$orderStatusList);
		$this->assign('syncStatusList',$syncStatusList);
		$this->assign('page',$show);
		$this->assign('filter',$filter);
		$this->display();
    }
    
    //确认收货
    public function confirmOrder($id = ''){
        if($orderInfo = D('Orders')->getOrdersInfo($id)){
		    if($orderInfo['status']!=3){
		        $ret = array('code'=>0,'message'=>'状态异常!');
			    $this->ajaxReturn($ret);
		    }
			$ret = M('orders')->where(['id'=>$id])->save(['status'=>4]);
			if($ret!==false){
			    $ret = array('code'=>1,'message'=>'操作成功!');
			    $this->ajaxReturn($ret);
			}else{
			    $ret = array('code'=>0,'message'=>'操作失败!');
			    $this->ajaxReturn($ret);
			}
		}else{
			$ret = array('code'=>0,'message'=>'不存在此订单号!');
			$this->ajaxReturn($ret);
		}
    }
    
    //发货
    public function deliverOrder($id = ''){
		if(IS_POST){
			$data = I('post.');
			$arr = [];
			$orderInfo = D('Orders')->getOrdersInfo($data['id']);
			if($orderInfo['status']!=2){
			    $ret = array('code'=>0,'message'=>'订单状态有误，无法操作');
			    $this->ajaxReturn($ret);
			}
			if(!$addressInfo = M('order_address')->where(['order_id'=>$orderInfo['order_id']])->find()){
		        $ret = array('code'=>0,'message'=>'缺少用户地址信息，无法操作');
			    $this->ajaxReturn($ret);
		    }
			$arr['order_id'] = $orderInfo['order_id'];
			$arr['express_type'] = 1;
			$arr['express_id'] = $data['express_id'];
			$info = D('Delivery')->getDeliveryInfo($data['express_id']);
			$arr['express_title'] = $info['name'];
			$arr['express_no'] = $data['express_no'];
			$arr['deliver_time'] = date('Y-m-d H:i:s',time());
			$arr['express_ship_name'] = $addressInfo['ship_name'];
			$arr['express_phone'] = $addressInfo['ship_mobile'];
			$arr['express_province_id'] = $addressInfo['province_id'];
			$arr['express_province'] = $addressInfo['province'];
			$arr['express_city_id'] = $addressInfo['city_id'];
			$arr['express_city'] = $addressInfo['city'];
			$arr['express_area_id'] = $addressInfo['area_id'];
			$arr['express_area'] = $addressInfo['area'];
			$arr['express_address'] = $addressInfo['address'];
			$arr['addtime'] = date('Y-m-d H:i:s',time());
			D('Orders')->startTrans();
			if(D('OrderExpress')->addOrderExpress($arr)){
            $ret = M('orders')->where(['id'=>$orderInfo['id']])->save(['status'=>3,'deliver_time'=>$arr['addtime']]);
            if($ret===false){
               D('Orders')->rollback();
               $ret = array('code'=>0,'message'=>'发货失败,更改订单状态失败');
            $this->ajaxReturn($ret);
            }
            //扣减库存
            $orderItemList = M('order_list')->where(['order_id'=>$orderInfo['order_id']])->select();
            if(is_array($orderItemList)&&count($orderItemList)>0){
               $logData = [];
               $logData['order_id'] = $orderInfo['order_id'];
               $logData['type'] = 'putout';
               $logData['op_name'] = session('login_name');
               $logData['addtime'] = date('Y-m-d H:i:s',time());
               foreach($orderItemList as $key=>$val){
                  if(!$goodsListInfo = M('goods_list')->where(['id'=>$val['goods_list_id']])->find()){
                        D('Orders')->rollback();
                        $ret = array('code'=>0,'message'=>'不存在此商品');
                     $this->ajaxReturn($ret);
                  }
                  $data = [];
                  $data['stocks'] = ($goodsListInfo['stocks']-$val['nums'])<0?0:($goodsListInfo['stocks']-$val['nums']);
                  $data['freez'] = ($goodsListInfo['freez']-$val['nums'])<0?0:($goodsListInfo['freez']-$val['nums']);
                  $ret = M('goods_list')->where(['id'=>$val['goods_list_id']])->save($data);
                  if($ret===false){
                     D('Orders')->rollback();
                     $ret = array('code'=>0,'message'=>'更新库存失败!');
                     $this->ajaxReturn($ret);
                  }
                  $logData['goods_id'] = $val['goods_id'];
                  $logData['goods_list_id'] = $val['goods_list_id'];
                  $logData['num'] = $val['nums'];
                  M('storage_logs')->add($logData);
               }
            }
            D('Orders')->commit();
            $ret = array('code'=>1,'message'=>'发货成功');
            $this->ajaxReturn($ret);
			}else{
            D('Orders')->rollback();
            $ret = array('code'=>0,'message'=>'发货失败');
            $this->ajaxReturn($ret);
			}
		}else{
			$deliverycorpList = D('Delivery')->getDeliveryAllList();
			$this->assign('deliverycorpList',$deliverycorpList);
			$this->assign('id',$id);
			$this->display();
		}
   }
    
    public function orderDetail(){
        $id = I('id','');
        $info = D('Orders')->getOrdersInfo($id);
        if(!empty($info['user_id'])){
			$userInfo = D('User')->getUserInfo($info['user_id']);
			$info['username'] = emojiDecode($userInfo['username']);
		}
        $itemsList = M('order_list')->where(['order_id'=>$info['order_id']])->select();
        if(is_array($itemsList)&&count($itemsList)>0){
            foreach($itemsList as &$val){
    			$goodsListInfo = M('goods_list')->where(['id'=>$val['goods_list_id']])->find();
				if(empty($goodsListInfo['goods_img_url'])){
					$goodsInfo = M('goods')->where(['id'=>$val['goods_id']])->find();
					$goodsListInfo['goods_img_url'] = $goodsInfo['goods_small_pic'];
				}
    			$val['img'] = $goodsListInfo['goods_img_url'];
            }
        }
        $deliverInfo = M('order_express')->where(['order_id'=>$info['order_id']])->find();
        $orderAddrInfo = M('order_address')->where(['order_id'=>$info['order_id']])->find();
		$this->assign('info',$info);
		$this->assign('deliverInfo',$deliverInfo);
		$this->assign('itemsList',$itemsList);
		$this->assign('orderAddrInfo',$orderAddrInfo);
		$this->display();
    }
    
    /*
	* Function:		orderRefundList
	* Description:	退款订单列表
	*/
    public function orderRefundList(){
		$filter = I('param.');
		$page =  I('get.p',1);
		$pageSize = 10;
		$filter = returnFilter($filter);
		$ordersList = D('OrderRefund')->getOrderRefundList($page,$filter,$pageSize);
		if(is_array($ordersList)&&count($ordersList)>0){
			foreach($ordersList as $key=>$val){
				if(!empty($val['user_id'])){
					$userInfo = D('User')->getUserInfo($val['user_id']);
					$ordersList[$key]['username'] = emojiDecode($userInfo['username']);
					$ordersList[$key]['avatarurl'] = $userInfo['avatarurl'];
				}
			}
		}
		$count =  D('OrderRefund')->getOrderRefundCount($filter);
		$pages = getpage($count,$pageSize,$filter);
		$show = $pages->show();
		$this->assign('ordersList',$ordersList);
		$this->assign('page',$show);
		$this->assign('filter',$filter);
		$this->display();
    }
    
    public function orderRefundDetail(){
        $id = I('id','');
        $info = D('OrderRefund')->getOrderRefundInfo($id);
        if(!empty($info['user_id'])){
			$userInfo = D('User')->getUserInfo($info['user_id']);
			$info['username'] = emojiDecode($userInfo['username']);
		}
        $itemsList = M('order_refund_list')->where(['tid'=>$info['id']])->select();
        if(is_array($itemsList)&&count($itemsList)>0){
            foreach($itemsList as &$val){
    			$goodsListInfo = M('goods_list')->where(['id'=>$val['goods_list_id']])->find();
    			$val['goods_spec'] = $goodsListInfo['goods_spec'];
    			$val['img'] = $goodsListInfo['goods_img_url'];
            }
        }
        $imageList = [];
        if(!empty($info['imgurl'])){
            $imageList = explode(',',$info['imgurl']);
        }
		$this->assign('info',$info);
		$this->assign('itemsList',$itemsList);
		$this->assign('imageList',$imageList);
		$this->display();
    }
    
    public function auitOrderRefund($id = ''){
		if(IS_POST){
			$arr = array();
			$data = I('post.');
			if(!$info = M('order_refund')->where(['id'=>$data['id']])->find()){
			    $ret = array('code'=>0,'message'=>'不存在此退款订单!');
				$this->ajaxReturn($ret);
			}
			if($data['auitSelect']==1){
			    $arr['status'] = 5;
			    if($info['type']==2){
			        $arr['status'] = 1;
			    }
				$arr['op_memo'] = '';
			}else if($data['auitSelect']==2){
				$arr['status'] = 7;
				if(empty($data['reason'])){
					$ret = array('code'=>0,'message'=>'审核不通过原因不能为空!');
					$this->ajaxReturn($ret);
				}
				$arr['op_memo'] = $data['reason'];
			}
			$ret = M('order_refund')->where(['id'=>$data['id']])->save($arr);
			if($ret!==false){
				$ret = array('code'=>1,'message'=>'提交成功!');
				$this->ajaxReturn($ret);
			}else{
				$ret = array('code'=>0,'message'=>'提交失败!');
				$this->ajaxReturn($ret);
			}
		}else{
			$this->assign('id',$id);
			$auitSelectList = array(array('value'=>1,'name'=>'通过'),array('value'=>2,'name'=>'不通过'));
			$this->assign('auitSelectList',$auitSelectList);
			$this->display();
		}
	}
	
	//确认商品收到
	public function confirmOrderRefund($id = ''){
		if($orderInfo = D('OrderRefund')->getOrderRefundInfo($id)){
		    if($orderInfo['status']!=2 && $orderInfo['status']!=1){
		        $ret = array('code'=>0,'message'=>'状态异常!');
			    $this->ajaxReturn($ret);
		    }
			$ret = M('order_refund')->where(['id'=>$id])->save(['status'=>5]);
			if($ret!==false){
			    $ret = array('code'=>1,'message'=>'操作成功!');
			    $this->ajaxReturn($ret);
			}else{
			    $ret = array('code'=>0,'message'=>'操作失败!');
			    $this->ajaxReturn($ret);
			}
		}else{
			$ret = array('code'=>0,'message'=>'不存在此订单号!');
			$this->ajaxReturn($ret);
		}
	}
	
	//商品退款
	public function completeOrderRefund($id = ''){
		if($orderInfo = D('OrderRefund')->getOrderRefundInfo($id)){
		    if(!$yOrderInfo = D('Orders')->getOrdersInfoByOrderId($orderInfo['y_order_id'])){
		        $rets = array('code'=>0,'message'=>'销售订单不存在');
			    $this->ajaxReturn($rets);
		    }
		    //退款接口
		    $ret = D('OrderRefund')->doRefund($yOrderInfo['order_id'],$yOrderInfo['total_amount']);
		    if(!empty($ret['code'])){
    			//修改退款订单状态
    			M('order_refund')->where(['id'=>$orderInfo['id']])->save(['status'=>6]);
    			//修改orders表状态为取消
    			M('orders')->where(['order_id'=>$yOrderInfo['order_id']])->save(['status'=>5]);
    			$itemList = M('order_list')->where(['order_id'=>$yOrderInfo['order_id']])->select();
    			if(is_array($itemList)&&count($itemList)>0){
    			    foreach($itemList as $key=>$val){
    			        M('goods')->where(['id'=>$val['goods_id']])->save(['sale_nums'=>['exp','sale_nums-'.$val['nums']]]);
    			    }
    			}
    			$rets = array('code'=>1,'message'=>'退款成功');
			   $this->ajaxReturn($rets);
		    }else{
		        $rets = array('code'=>0,'message'=>$ret['errorMsg']);
			    $this->ajaxReturn($rets);
		    }
		}else{
			$ret = array('code'=>0,'message'=>'不存在此订单号!');
			$this->ajaxReturn($ret);
		}
	}

   //取消订单
   public function cancelOrder($id = ''){
      $orderInfo = D('Orders')->getOrdersInfo($id);
      if(!in_array($orderInfo['status'],[0,1,2])){
         $ret = array('code'=>0,'message'=>'订单状态有误，无法操作');
         $this->ajaxReturn($ret);
      }
      if(in_array($orderInfo['status'],[0,1])){
         $ret = M('orders')->where(['id'=>$id])->save(['status'=>5]);
    	   if($ret===false){
            $ret = array('code'=>0,'message'=>'操作失败');
			   $this->ajaxReturn($ret);
         }
      }else{//已支付
         if($orderInfo['is_pay']==1){
            $result = D('OrderRefund')->doRefund($orderInfo['order_id'],$orderInfo['total_amount']);
            if(!empty($result['code'])){
               $ret = M('orders')->where(['order_id'=>$orderInfo['order_id']])->save(['status'=>5]);
               if($ret===false){
                  $ret = array('code'=>0,'message'=>'操作失败01');
                  $this->ajaxReturn($ret);
               }
            }else{
               $ret = array('code'=>0,'message'=>$result['errorMsg']);
               $this->ajaxReturn($ret);
            }
         }
      }
      //扣减库存
      $orderItemList = M('order_list')->where(['order_id'=>$orderInfo['order_id']])->select();
      if(is_array($orderItemList)&&count($orderItemList)>0){
         foreach($orderItemList as $key=>$val){
            if(!$goodsListInfo = M('goods_list')->where(['id'=>$val['goods_list_id']])->find()){
               continue;
            }
            $data = [];
            $data['freez'] = ($goodsListInfo['freez']-$val['nums'])<0?0:($goodsListInfo['freez']-$val['nums']);
            $ret = M('goods_list')->where(['id'=>$val['goods_list_id']])->save($data);
            if($ret===false){
               continue;
            }
            M('goods')->where(['id'=>$val['goods_id']])->save(['sale_nums'=>['exp','sale_nums-'.$val['nums']]]);
         }
      }
      $ret = array('code'=>1,'message'=>'操作成功');
      $this->ajaxReturn($ret);
   }
	
	//批量推送订单
	public function batchSendOrder($order_id = ''){
// 		$ret = array('code'=>0,'message'=>'开发中...');
// 		$this->ajaxReturn($ret);
		$flag = 0;
		$retMsg = '';
		$sucessMsg = '';
		$orderArr = explode('_',trim($order_id,'_'));
		if(is_array($orderArr) && count($orderArr)>0){
			foreach($orderArr as $k=>$v){
				if($orderInfo = D('Orders')->getOrdersInfoByOrderId($v)){
					if($orderInfo['status']!=2){
						$retMsg .= '订单号:'.$v.',订单状态有误，不能执行同步操作！<br/>';
						continue;
					}
					if($orderInfo['sync_status']===1){
						$retMsg .= '订单号:'.$v.',已同步，请不要重复操作！<br/>';
						continue;
					}
					$apiRet = D('ApiPlantform')->addGuanYiOrders($v);
					if(!empty($apiRet)){
					    if(!empty($apiRet['success'])){
    						$ret = M('orders')->where(['order_id'=>$v])->save(['sync_status'=>1,'sync_time'=>date('Y-m-d H:i:s',time()),'memo'=>'']);
    						if($ret!==false){
    						    $flag++;
    						}else{
    						    $retMsg .= '订单号:'.$v.',更新订单状态失败！<br/>';
    						}
    					}else{
    					    $retMsg .= '订单号:'.$v.',接口错误：'.$apiRet['errorDesc'].'<br/>';
    					}
					}else{
						$retMsg .= D('ApiPlantform')->get_error();
					}
				}else{
					$retMsg .= '订单号:'.$v.',不存在此订单号！<br/>';
				}
			}
			if(!empty($flag)){
				$sucessMsg = '成功同步了'.$flag.'个订单<br/>';
				$return['code'] = 1;
			}else{
				$return['code'] = 0;
			}
			if(!empty($retMsg)){
				$sucessMsg .= '错误信息:'.$retMsg;
			}
			$return['message'] = $sucessMsg;
			$this->ajaxReturn($return);
		}else{
			$return = array('code'=>0,'message'=>'请选择订单');
			$this->ajaxReturn($return);
		}
	}
	
	//批量获取运单号
	public function batchGetOrderDelivery($order_id = ''){
// 		$ret = array('code'=>0,'message'=>'开发中...');
// 		$this->ajaxReturn($ret);
		$flag = 0;
		$retMsg = '';
		$sucessMsg = '';
		$orderArr = explode('_',trim($order_id,'_'));
		if(is_array($orderArr) && count($orderArr)>0){
			foreach($orderArr as $k=>$v){
				if($orderInfo = D('Orders')->getOrdersInfoByOrderId($v)){
					if($orderInfo['status']!=2){
						$retMsg .= '订单号:'.$v.',订单状态有误，不能执行同步操作！<br/>';
						continue;
					}
					if($orderInfo['sync_status']!=1){
						$retMsg .= '订单号:'.$v.',未同步！<br/>';
						continue;
					}
					$res = D('ApiPlantform')->getGuanYiOrders($v);
					if(!empty($res)){
					    if(!empty($res['success'])){
					        $ret = $res['orders'][0];
    					    if(empty($ret['deliverys'][0]['delivery'])){
    					        $retMsg .= '订单号:'.$v.',还未发货！<br/>';
    						    continue;
    					    }
    						//逻辑操作
    						if(!$addressInfo = M('order_address')->where(['order_id'=>$orderInfo['order_id']])->find()){
                			    $retMsg .= '订单号:'.$v.',缺少用户地址信息！<br/>';
    						    continue;
                		    }
                			$arr['order_id'] = $orderInfo['order_id'];
                			$arr['express_type'] = 1;
                			if(!$deliverInfo = D('Delivery')->getDeliveryInfoByCode($ret['deliverys'][0]['express_code'])){
                			    $retMsg .= '订单号:'.$v.',不存在此快递配置方式'.$ret['deliverys'][0]['express_code'].'！<br/>';
    						    continue;
                			}
                			$arr['express_id'] = $deliverInfo['id'];
                			$arr['express_title'] = $deliverInfo['name'];
                			$arr['express_no'] = $ret['deliverys'][0]['mail_no'];
                			$arr['deliver_time'] = $ret['orders'][0]['modifytime'];
                			$arr['express_ship_name'] = $addressInfo['ship_name'];
                			$arr['express_phone'] = $addressInfo['ship_mobile'];
                			$arr['express_province_id'] = $addressInfo['province_id'];
                			$arr['express_province'] = $addressInfo['province'];
                			$arr['express_city_id'] = $addressInfo['city_id'];
                			$arr['express_city'] = $addressInfo['city'];
                			$arr['express_area_id'] = $addressInfo['area_id'];
                			$arr['express_area'] = $addressInfo['area'];
                			$arr['express_address'] = $addressInfo['address'];
                			$arr['addtime'] = date('Y-m-d H:i:s',time());
                			D('Orders')->startTrans();
                			if(D('OrderExpress')->addOrderExpress($arr)){
                			    $result = M('orders')->where(['id'=>$orderInfo['id']])->save(['status'=>3,'deliver_time'=>$arr['addtime']]);
                			    if($result===false){
                			        D('Orders')->rollback();
                			    	$retMsg .= '订单号:'.$v.',发货失败,更改订单状态失败！<br/>';
    						        continue;
                			    }
                			    //扣减库存
                			    $orderItemList = M('order_list')->where(['order_id'=>$orderInfo['order_id']])->select();
                			    if(is_array($orderItemList)&&count($orderItemList)>0){
                			        $logData = [];
                        			$logData['order_id'] = $orderInfo['order_id'];
                        			$logData['type'] = 'putout';
                        			$logData['op_name'] = session('login_name');
                        			$logData['addtime'] = date('Y-m-d H:i:s',time());
                			        foreach($orderItemList as $key=>$val){
                			            if(!$goodsListInfo = M('goods_list')->where(['id'=>$val['goods_list_id']])->find()){
                			    	        D('Orders')->rollback();
                        			    	$retMsg .= '订单号:'.$v.',不存在此商品'.$val['goods_list_id'].'！<br/>';
            						        continue;
                			            }
                			            $data = [];
                    			        $data['stocks'] = ($goodsListInfo['stocks']-$val['nums'])<0?0:($goodsListInfo['stocks']-$val['nums']);
                    			        $data['freez'] = ($goodsListInfo['freez']-$val['nums'])<0?0:($goodsListInfo['freez']-$val['nums']);
                    			        $result = M('goods_list')->where(['id'=>$val])->save($data);
                    			        if($result===false){
                    					    D('Orders')->rollback();
                        			    	$retMsg .= '订单号:'.$v.',更新库存失败'.$val['goods_list_id'].'！<br/>';
            						        continue;
                    			        }
                			            $logData['goods_id'] = $val['goods_id'];
                			            $logData['goods_list_id'] = $val['goods_list_id'];
                			            $logData['num'] = $val['nums'];
                			            M('storage_logs')->add($logData);
                			        }
                			    }
                			    D('Orders')->commit();
                			}
    					}else{
    					    $retMsg .= '订单号:'.$v.',接口错误：'.$res['errorDesc'].'<br/>';
    					}
					}else{
						$retMsg .= D('ApiPlantform')->get_error();
					}
				}else{
					$retMsg .= '订单号:'.$v.',不存在此订单号！<br/>';
				}
			}
			if(!empty($flag)){
				$sucessMsg = '成功同步了'.$flag.'个订单<br/>';
				$return['code'] = 1;
			}else{
				$return['code'] = 0;
			}
			if(!empty($retMsg)){
				$sucessMsg .= '错误信息:'.$retMsg;
			}
			$return['message'] = $sucessMsg;
			$this->ajaxReturn($return);
		}else{
			$return = array('code'=>0,'message'=>'请选择订单');
			$this->ajaxReturn($return);
		}
	}
}